<!--
 * @Description:
 * @version:
 * @Author: 尹鹏孝
 * @Date: 2023-03-21 11:22:24
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2023-03-23 09:45:33
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>iterator遍历器</title>
</head>
<body>
<!-- 为Array，Object，Map，Set提供不同数据接口遍历操作的接口。
按照某种次序排序
遍历for of -->


<script>
    var it = makeIterator(['a','b']);
    it.next();
    it.next()

    function makeIterator(arr){
        var nextIndex =0;
        return {
            next:function(){
                return nextIndex<arr.length?{value:arr[nextIndex++],done:false}:{
                    value:undefined,
                    done:true
                }
            }
        }
    }

    // iterable:可遍历，Symbol.iterator
    const obj={
        [Symbol.iterator]:function(){
            return {
                next:function(){
                    return {
                        value:1,
                        done:true
                    }
                }
            }
        }
    }
    obj
    let arr=[1,2,3]
    let iter = arr[Symbol.iterator]();
    iter.next();
    iter.next();
    iter.next();
    iter.next();
    let iterable={
        0:'a',
        1:'b',
        2:'c',
        length:3,
        [Symbol.iterator]:Array.prototype[Symbol.iterator]
    }

    for(let m of iterable){
        console.log(m)
    }

    //调用Iterator接口的场合
    let set = new Set().add('a1').add('b1').add('c1');
    let [m,y]=set;
    console.log(m)
    console.log(y)
    let [first,...reset]=set;
    console.log(first);
    console.log(reset);

    var str ='hello'
   console.log([...str])
   var arrNew = ['a', 'b', 'c', 'd'];

    for (let a in arrNew) {
        console.log(a); // 0 1 2 3
    }

    for (let a of arrNew) {
        console.log(a); // a b c d
    }
    let myIterable ={
       [Symbol.iterator]: function* () {
            yield 1;
            yield 2;
            yield 3;
        }
    };
   [...myIterable] ;

    let obj1 = {
        *[Symbol.iterator](){
            yield 'hello';
            yield 'world';
        }
    }

    for(let x of obj1){
        console.log(x);
    }
</script>


</body>
</html>